﻿using NationalInstruments.DAQmx;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.OpenXmlFormats.Dml.Chart;
using ScottPlot;
using Serilog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using 低频天线阵列相控阵信号发生系统SmartFASK12.Controls;
using 低频天线阵列相控阵信号发生系统SmartFASK12.Models;
using 低频天线阵列相控阵信号发生系统SmartFASK12.Properties;
using 低频天线阵列相控阵信号发生系统SmartFASK12.View;
using 低频天线阵列相控阵信号发生系统SmartFASK12.View.AdjustDemodulation.Views;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;

namespace 低频天线阵列相控阵信号发生系统SmartFASK12.View.AdjustDemodulation
{
    public partial class Form1 : Form
    {
        private Uc_Modulation _uc_Modulation = new Uc_Modulation();
        private Uc_Demodulation _uc_Demodulation = new Uc_Demodulation();

        private bool isImport = false;
        #region 变量

        /// <summary>
        /// 手动采集
        /// </summary>
        private bool IsManual;

        /// <summary>
        /// 输出电压
        /// </summary>
        private CalSingalInfo _calSingalInfo = null;

        /// <summary>
        /// 采集数据
        /// </summary>
        private double[] _yvalues;
        /// <summary>
        /// 解调数据
        /// </summary>
        private MJietiaoShowResultFSK2 _mJietiao = null;

        #endregion

        #region 属性

    

        #endregion

        public Form1()
        {
            InitializeComponent();

            //以下表示在程序运行目录 以天为单位生成日志文件(也可以以小时等为单位)
            Log.Logger = new LoggerConfiguration()
               .MinimumLevel.Debug()
               .WriteTo.File("logs\\log.log", rollingInterval: RollingInterval.Day)
               .CreateLogger();

            Init();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {

            this.groupBox_Uc_Modulation.Controls.Add(this._uc_Modulation);
            this.panel_Uc_Demodulation.Controls.Add(this._uc_Demodulation);

            formsPlot_realtimedata.Plot.Title("原始数据");
            formsPlot_ValidData.Plot.Title("过滤后数据");
            formsPlot_FFT.Plot.Title("过滤后FFT");
            formsPlot_Orig1.Plot.Title("滤波1后原始数据");
            formsPlot_FFT1.Plot.Title("滤波1后FFT");
            formsPlot_Bao1.Plot.Title("滤波1后包络数据");
            formsPlot_Orig2.Plot.Title("滤波2后原始数据");
            formsPlot_FFT2.Plot.Title("滤波2后FFT");
            formsPlot_Bao2.Plot.Title("滤波2后包络数据");
            formsPlot_Bao.Plot.Title("包络数据对比");
            formsPlot_Judge.Plot.Title("判决数据");
            formsPlot_JieTiao.Plot.Title("解调结果");

            //读取Config
            if (!File.Exists(MPublic.ConfigFilePath))
            {
                MessageBox.Show("初始化失败，Config文件不存在！", "提示");
                Environment.Exit(0);
            }
            //开始执行
            MEvent.Singleton().HasSendVoltage += Form1_HasSendVoltage;
            //开始执行
            MEvent.Singleton().HasStartExecution += Form1_HasStartExecution;
            //电压完成
            MEvent.Singleton().HasVoltageOutputCompleted += Form1_HasVoltageOutputCompleted;
            //显示抽样判决点
            MEvent.Singleton().HasShowJudgePoint += Form1_HasShowJudgePoint;
            //更新显示点数
            MEvent.Singleton().HasUpdataShowPoint += Form1_HasUpdataShowPoint;
            //解调
            MEvent.Singleton().HasDemodulation += Form1_HasDemodulation;
            //开始采集
            MEvent.Singleton().HasStartCollection += Form1_HasStartCollection;
            //停止采集
            MEvent.Singleton().HasStopAcquisition += Form1_HasStopAcquisition;
            //导出Excel
            MEvent.Singleton().HasExcelOut += Form1_HasExcelOut;
            // 导入Excel
            MEvent.Singleton().HasImportExcel += Form1_HasImportExcel;
            //初始化FFT计算
            Thread thread = new Thread(InitFFT_MATLAB)
            {
                IsBackground = true
            };
            thread.Start();
        }

        /// <summary>
        /// 发送电压
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Form1_HasSendVoltage(object sender, SampleQuantityMode e)
        {
            isImport = false;
            List<double> Data = new List<double>();
            List<double> Data2 = new List<double>();
            _uc_Demodulation.SaveConfig();
            _uc_Modulation.SaveConfig();
            if (MPublic.ConfigModel2.modulationMode == 0)
            {
                //4431
                if (MPublic.ConfigModel2.acquisitionCard == 0)
                {
                    _calSingalInfo = MJietiao.Singleton().CalSingalASK(MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalfrequency_modulate),
                        MConvert.Singleton().KToInt(MPublic.ConfigModel2.samplingrate_modulate),
                         MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency1_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude1_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard1_modulate),
                                                                   MPublic.ConfigModel2.dutyCycle,
                                                                   MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalnumber),
                                                                  MPublic.ConfigModel2.signalType_modulate, MPublic.ConfigModel2.signalsequence);

                    Data.AddRange(_calSingalInfo.res);
                }
                //6218
                else if (MPublic.ConfigModel2.acquisitionCard == 1)
                {
                    _calSingalInfo = MJietiao.Singleton().CalSingalASK(
                        MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalfrequency_modulate),
                        MConvert.Singleton().KToInt(MPublic.ConfigModel2.samplingrate_modulate),
                         MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency1_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude1_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard1_modulate),
                                                                    MPublic.ConfigModel2.phase1,
                                                                   MPublic.ConfigModel2.dutyCycle,
                                                                   MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalnumber),
                                                                   MPublic.ConfigModel2.signalType_modulate,
                                                                   MPublic.ConfigModel2.signalsequence);

                    Data.AddRange(_calSingalInfo.res);

                    _calSingalInfo = MJietiao.Singleton().CalSingalASK(MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalfrequency_modulate),
                       MConvert.Singleton().KToInt(MPublic.ConfigModel2.samplingrate_modulate),
                        MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency2_modulate),
                                                                  MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude2_modulate),
                                                                  MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard2_modulate),
                                                                   MPublic.ConfigModel2.phase2,
                                                                  MPublic.ConfigModel2.dutyCycle,
                                                                  MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalnumber),
                                                                  MPublic.ConfigModel2.signalType_modulate,
                                                                  _calSingalInfo.numberSignal,
                                                                  _calSingalInfo.numberSignals);

                    Data2.AddRange(_calSingalInfo.res);
                }
            }
            else if (MPublic.ConfigModel2.modulationMode == 1)
            {
                //4431
                if (MPublic.ConfigModel2.acquisitionCard == 0)
                {
                    //生成电压
                    _calSingalInfo = MJietiao.Singleton().CalSingal2(MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalfrequency_modulate),
                                                               MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalnumber),
                                                               MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency1_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude1_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard1_modulate),
                                                               MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency2_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude2_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard2_modulate),
                                                               MPublic.ConfigModel2.signalType_modulate,
                                                               MPublic.ConfigModel2.signalsequence);

                    Data.AddRange(_calSingalInfo.res);
                }
                //6218
                else if (MPublic.ConfigModel2.acquisitionCard == 1)
                {
                    //生成电压
                    _calSingalInfo = MJietiao.Singleton().CalSingalFSK2(MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalfrequency_modulate),
                                                               MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalnumber),
                                                               MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency1_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude1_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard1_modulate),
                                                               MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency2_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude2_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard2_modulate),
                                                               MPublic.ConfigModel2.phase1,
                                                               MPublic.ConfigModel2.signalType_modulate,
                                                               MPublic.ConfigModel2.signalsequence,
                                                               MPublic.ConfigModel2.dutyCycle);
                    Data.AddRange(_calSingalInfo.res);

                    if (!string.IsNullOrEmpty(MPublic.ConfigModel2.physicalChannel))
                    {
                        _calSingalInfo = MJietiao.Singleton().CalSingalFSK2(MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalfrequency_modulate),
                                                                   MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalnumber),
                                                                   MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency1_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude1_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard1_modulate),
                                                                   MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency2_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude2_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard2_modulate),
                                                                   MPublic.ConfigModel2.phase2,
                                                                   _calSingalInfo.numberSignal,
                                                                   MPublic.ConfigModel2.dutyCycle);
                        Data2.AddRange(_calSingalInfo.res);
                    }
                }
            }
            string msg;
            if (Data2.Count <= 0)
                //初始化发射电压
                 msg = MNI2.Singleton().OutputOoltage(MPublic.ConfigModel2, Data.ToArray(), e, null);
            else
                //初始化发射电压
                 msg = MNI2.Singleton().OutputOoltage(MPublic.ConfigModel2, Data.ToArray(), e, Data2.ToArray());

            if (msg != null)
            {
                MessageBox.Show(msg, "提示");
                return;
            }

            MNI2.Singleton().myTask.Start();

            //修改状态
            _uc_Modulation.IsStart_Export = true;
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Form1_HasExcelOut(object sender, EventArgs e)
        {
            // 对话框
            SaveFileDialog sfd = new SaveFileDialog();
            //设置保存文件对话框的标题
            sfd.Title = "请选择要保存的文件路径";
            //初始化保存目录，默认exe文件目录
            sfd.InitialDirectory = Application.StartupPath;
            //设置保存文件的类型
            sfd.Filter = "EXCEL|*.xlsx";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                //获得保存文件的路径
                string filePath = sfd.FileName;
                if (!MExcel.Singleton().ToExcel_NPOI(_yvalues, filePath))
                {
                    MessageBox.Show("导出数据时发生了异常！", "异常");
                }
            }
        }

        /// <summary>
        /// 停止采集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Form1_HasStopAcquisition(object sender, EventArgs e)
        {
            _uc_Demodulation.IsStart_Gather = false;
        }

        /// <summary>
        /// 开始采集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Form1_HasStartCollection(object sender, bool e)
        {
            IsManual = e;
            Thread thread = new Thread(DataCollection_Thread);
            thread.IsBackground = false;
            thread.Start();

            _uc_Demodulation.IsStart_Gather = true;
        }

        /// <summary>
        /// 解调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Form1_HasDemodulation(object sender, EventArgs e)
        {
            #region 参数转换
            int samplefre = MConvert.Singleton().KToInt(MPublic.ConfigModel2.samplesPerBuffer_gather);
            int fre1 = MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency1);
            int bandwidth1 = MConvert.Singleton().KToInt(MPublic.ConfigModel2.amplitude1);
            int order1 = MConvert.Singleton().KToInt(MPublic.ConfigModel2.filtercoefficient1);
            int fre2 = MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency2);
            int bandwidth2 = MConvert.Singleton().KToInt(MPublic.ConfigModel2.amplitude2);
            int order2 = MConvert.Singleton().KToInt(MPublic.ConfigModel2.filtercoefficient2);
            int shift = Convert.ToInt32(MPublic.ConfigModel2.shifting);
            int signalFre = MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalfrequency);
            double midValue = Convert.ToDouble(MPublic.ConfigModel2.midValue);
            double checkValue = Convert.ToDouble(MPublic.ConfigModel2.checkValue);
            int showpoints = MConvert.Singleton().KToInt(MPublic.ConfigModel2.showpoints);
            int continuousquantity = MConvert.Singleton().KToInt(MPublic.ConfigModel2.continuousquantity);
            #endregion

            #region 解调

            // FSK
            if (MPublic.ConfigModel2.modulationMode == 1)
            {

                _mJietiao = MJietiao.Singleton().JietiaoFSK3_2(_yvalues.ToList(),
                                                samplefre,
                                                fre1,
                                                bandwidth1,
                                                order1,
                                                fre2,
                                                bandwidth2,
                                                order2,
                                                shift,
                                                signalFre,
                                                MPublic.ConfigModel2.gyh,
                                                MPublic.ConfigModel2.zdbcdygz,
                                                MPublic.ConfigModel2.buValue,
                                                midValue,
                                                checkValue);
            }
            // ASK
            else if (MPublic.ConfigModel2.modulationMode == 0)
            {
                _mJietiao = MJietiao5.Singleton().JietiaoASK(_yvalues.ToList(),
                                               samplefre,
                                               fre1,
                                               bandwidth1,
                                               order1,
                                               shift,
                                               signalFre,
                                               showpoints,
                                               continuousquantity,
                                               midValue,
                                               checkValue);
            }

            #endregion

            if (_mJietiao == null)
            {
                MessageBox.Show("解调发生了异常", "提示");
                return;
            }

            //解调显示
            DemodulationDisplay();
        }

        /// <summary>
        /// 更新显示点数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_HasUpdataShowPoint(object sender, EventArgs e)
        {
            DemodulationDisplay();
        }

        /// <summary>
        /// 显示抽样判决点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Form1_HasShowJudgePoint(object sender, EventArgs e)
        {
            //显示点数
            int showpoints = MConvert.Singleton().KToInt(MPublic.ConfigModel2.showpoints);
            //显示点数
            int startShowpoints = MConvert.Singleton().KToInt(MPublic.ConfigModel2.startShowpoints);

            List<double> Judge_X = _mJietiao.Judge_X.Select(i => (double)i).Skip(startShowpoints).Take(showpoints).ToList();
            List<double> Judge_Y = _mJietiao.Judge_Y.Select(i => (double)i).Skip(startShowpoints).Take(showpoints).ToList();

            double maxJudge = Judge_X.Max();
            List<double> ChouYang_X = new List<double>();
            for (int i = 0; i < _mJietiao.ChouYang_X.Count; i++)
            {
                if (maxJudge < _mJietiao.ChouYang_X[i])
                    break;

                ChouYang_X.Add(_mJietiao.ChouYang_X[i]);
            }
            List<double> ChouYang_Y = _mJietiao.ChouYang_Y.Select(i => (double)i).Take(ChouYang_X.Count).ToList();

            formsPlot_Judge.Plot.Clear();
            //formsPlot_Judge
            FormsPlot(formsPlot_Judge, Judge_X, Judge_Y);
            //ChouYang
            if (MPublic.ConfigModel2.showJudgePoint && ChouYang_X.Count > 0 && ChouYang_Y.Count > 0)
                formsPlot_Judge.Plot.AddScatterPoints(ChouYang_X.ToArray(), ChouYang_Y.ToArray(), Color.Red);

            formsPlot_Judge.Plot.AxisAuto();
            formsPlot_Judge.Refresh();
        }

        /// <summary>
        /// 开始执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Form1_HasStartExecution(object sender, EventArgs e)
        {
            isImport = false;
            List<double> Data = new List<double>();
            List<double> Data2 = new List<double>();
            _uc_Demodulation.SaveConfig();
            _uc_Modulation.SaveConfig();
            if (MPublic.ConfigModel2.modulationMode == 0)
            {
                //4431
                if (MPublic.ConfigModel2.acquisitionCard == 0)
                {
                    _calSingalInfo = MJietiao.Singleton().CalSingalASK(MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalfrequency_modulate),
                        MConvert.Singleton().KToInt(MPublic.ConfigModel2.samplingrate_modulate),
                         MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency1_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude1_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard1_modulate),
                                                                   MPublic.ConfigModel2.dutyCycle,
                                                                   MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalnumber),
                                                                  MPublic.ConfigModel2.signalType_modulate, MPublic.ConfigModel2.signalsequence);

                    Data.AddRange(_calSingalInfo.res);
                }
                //6218
                else if (MPublic.ConfigModel2.acquisitionCard == 1)
                {
                    _calSingalInfo = MJietiao.Singleton().CalSingalASK(
                        MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalfrequency_modulate),
                        MConvert.Singleton().KToInt(MPublic.ConfigModel2.samplingrate_modulate),
                         MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency1_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude1_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard1_modulate),
                                                                    MPublic.ConfigModel2.phase1,
                                                                   MPublic.ConfigModel2.dutyCycle,
                                                                   MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalnumber),
                                                                   MPublic.ConfigModel2.signalType_modulate,
                                                                   MPublic.ConfigModel2.signalsequence);

                    Data.AddRange(_calSingalInfo.res);

                    _calSingalInfo = MJietiao.Singleton().CalSingalASK(MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalfrequency_modulate),
                       MConvert.Singleton().KToInt(MPublic.ConfigModel2.samplingrate_modulate),
                        MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency2_modulate),
                                                                  MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude2_modulate),
                                                                  MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard2_modulate),
                                                                   MPublic.ConfigModel2.phase2,
                                                                  MPublic.ConfigModel2.dutyCycle,
                                                                  MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalnumber),
                                                                  MPublic.ConfigModel2.signalType_modulate,
                                                                  _calSingalInfo.numberSignal,
                                                                  _calSingalInfo.numberSignals);

                    Data2.AddRange(_calSingalInfo.res);
                }
            }
            else if (MPublic.ConfigModel2.modulationMode == 1)
            {
                //4431
                if (MPublic.ConfigModel2.acquisitionCard == 0)
                {
                    //生成电压
                    _calSingalInfo = MJietiao.Singleton().CalSingal2(MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalfrequency_modulate),
                                                               MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalnumber),
                                                               MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency1_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude1_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard1_modulate),
                                                               MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency2_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude2_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard2_modulate),
                                                               MPublic.ConfigModel2.signalType_modulate,
                                                               MPublic.ConfigModel2.signalsequence);

                    Data.AddRange(_calSingalInfo.res);
                }
                //6218
                else if (MPublic.ConfigModel2.acquisitionCard == 1)
                {
                    //生成电压
                    _calSingalInfo = MJietiao.Singleton().CalSingalFSK2(MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalfrequency_modulate),
                                                               MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalnumber),
                                                               MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency1_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude1_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard1_modulate),
                                                               MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency2_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude2_modulate),
                                                               MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard2_modulate),
                                                               MPublic.ConfigModel2.phase1,
                                                               MPublic.ConfigModel2.signalType_modulate,
                                                               MPublic.ConfigModel2.signalsequence,
                                                               MPublic.ConfigModel2.dutyCycle);
                    Data.AddRange(_calSingalInfo.res);

                    if (!string.IsNullOrEmpty(MPublic.ConfigModel2.physicalChannel))
                    {
                        _calSingalInfo = MJietiao.Singleton().CalSingalFSK2(MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalfrequency_modulate),
                                                                   MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalnumber),
                                                                   MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency1_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude1_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard1_modulate),
                                                                   MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency2_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.amplitude2_modulate),
                                                                   MConvert.Singleton().KToDouble(MPublic.ConfigModel2.standard2_modulate),
                                                                   MPublic.ConfigModel2.phase2,
                                                                   _calSingalInfo.numberSignal,
                                                                   MPublic.ConfigModel2.dutyCycle);
                        Data2.AddRange(_calSingalInfo.res);
                    }
                }
            }
            string msg;
            if (Data2.Count <= 0)
                //初始化发射电压
                msg = MNI2.Singleton().OutputOoltage(MPublic.ConfigModel2, Data.ToArray(), SampleQuantityMode.FiniteSamples, null);
            else
                //初始化发射电压
                msg = MNI2.Singleton().OutputOoltage(MPublic.ConfigModel2, Data.ToArray(), SampleQuantityMode.FiniteSamples, Data2.ToArray());

            if (msg != null)
            {
                MessageBox.Show(msg, "提示");
                return;
            }

            _uc_Demodulation.SaveConfig();
            //开始采集发射电压
            Thread thread = new Thread(DataCollection_Thread)
            {
                IsBackground = false
            };
            thread.Start();

            _uc_Demodulation.IsStart_Gather = true;

            Thread.Sleep(1000);

            //发射电压
            MNI2.Singleton().myTask.Start();

            //修改状态
            _uc_Modulation.IsStart_Export = true;
        }

        /// <summary>
        /// 初始化_MATLAB计算程序
        /// </summary>
        private void InitFFT_MATLAB()
        {
            MyMatlab.FFTre(new List<double>()
            {
                1
            });
        }

        /// <summary>
        /// 数据采集
        /// </summary>
        private void DataCollection_Thread()
        {
            if (IsManual)
            {
                while (_uc_Demodulation.IsStart_Gather)
                {
                    _yvalues = MNI2.Singleton().CollectVoltage(MPublic.ConfigModel2, IsManual);

                    //_yvalues = MExcel.Singleton().Excel_ReadImportData_NPOI().ToArray();

                    _calSingalInfo = new CalSingalInfo();
                    _calSingalInfo.res = _yvalues.ToList();

                    if (_yvalues == null || _yvalues?.Length <= 0)
                    {
                        MessageBox.Show("NI通讯发生了异常", "提示");
                        return;
                    }

                    List<double> _xvalues = new List<double>();
                    double interval = 1.0 / MConvert.Singleton().KToInt(MPublic.ConfigModel2.samplesPerBuffer_gather);
                    double cx = 0;
                    for (int i = 0; i < _yvalues.Length; i++)
                    {
                        _xvalues.Add(cx);
                        cx += interval;
                    }

                    MData ffts = MyMatlab2.FFT(_yvalues.ToList(), MConvert.Singleton().KToInt(MPublic.ConfigModel2.samplesPerBuffer_gather));
                    List<double> yffts = new List<double>();
                    List<double> xffts = new List<double>();

                    this.BeginInvoke(new Action(() =>
                    {
                        FormsPlot(formsPlot_realtimedata, _xvalues, _yvalues.ToList());

                        FormsPlot(formsPlot_FFT, ffts.XValues, ffts.YValues);

                        _uc_Demodulation.IsStart_Gather = false;
                    }));
                }
            }
            else
            {
                _yvalues = MNI2.Singleton().CollectVoltage(MPublic.ConfigModel2);
                if (_yvalues == null || _yvalues?.Length <= 0)
                {
                    MessageBox.Show("NI通讯发生了异常", "提示");
                    return;
                }

                List<double> _xvalues = new List<double>();
                double interval = 1.0 / MConvert.Singleton().KToInt(MPublic.ConfigModel2.samplesPerBuffer_gather);
                double cx = 0;
                for (int i = 0; i < _yvalues.Length; i++)
                {
                    _xvalues.Add(cx);
                    cx += interval;
                }

                this.BeginInvoke(new Action(() =>
                {
                    FormsPlot(formsPlot_realtimedata, _xvalues, _yvalues.ToList());

                    _uc_Demodulation.IsStart_Gather = false;

                    Form1_HasDemodulation(this, null);
                }));
            }
        }

        /// <summary>
        /// 解调显示
        /// </summary>
        private void DemodulationDisplay()
        {
            //显示点数
            int showpoints = MConvert.Singleton().KToInt(MPublic.ConfigModel2.showpoints);
            //去除前点数
            int startShowpoints = MConvert.Singleton().KToInt(MPublic.ConfigModel2.startShowpoints);

            #region 处理解调

            MData ffts = MyMatlab2.FFT(_mJietiao.YValues, MConvert.Singleton().KToInt(MPublic.ConfigModel2.samplesPerBuffer_gather));

            #region

            // FSK
            if (MPublic.ConfigModel2.commissioningmode == 1)
            {
                string res = null;
                int count = 0;
                for (int i = 0; i < _calSingalInfo.numberSignal.Count; i++)
                {

                    res += _calSingalInfo.numberSignal[i];
                    if (_mJietiao.ResultInfo.JudgeResult.Count - 1 < i)
                    {
                        count++;
                        continue;
                    }
                    int judeg = _mJietiao.ResultInfo.JudgeResult[i];
                    int numberSignal = _calSingalInfo.numberSignal[i];
                    if (numberSignal != judeg)
                        count++;
                }

                //StringCompute stringcompute1 = new StringCompute();
                //stringcompute1.SpeedyCompute(res, _mJietiao.ResultInfo.GetDigitalSignal());  // 计算相似度， 不记录比较时间
                //decimal rate = stringcompute1.ComputeResult.Rate;     // 相似度百分之几，完全匹配相似度为1
                double rate = ((double)count / (double)_calSingalInfo.numberSignal.Count) * 100;
                rate = Math.Round(rate, 2);

                int TotalCount = _calSingalInfo.numberSignal.Count;
                int OneCount = _calSingalInfo.numberSignal.Sum();
                int ZeroCount = TotalCount - OneCount;
                string str = null;
                if (MPublic.ConfigModel2.signalType_modulate != 3)
                {
                    str = string.Format("总数：{0}，1个数：{1}，0个数：{2}\r\n", TotalCount, OneCount, ZeroCount) + res;



                    //显示数字信号
                    _uc_Modulation.EmitShowNumberSignal(str);
                }
                else
                {
                    //str = res;
                }

                richTextBox_Result.Text = _mJietiao.ResultInfo.GetString(rate);
            }
            // ASK
            else
            {
                if (MPublic.ConfigModel2.zdbcdygz)
                {
                    _calSingalInfo.numberSignals.Insert(0, MPublic.ConfigModel2.buValue);
                }

                if (!isImport)
                {
                    string res = null;
                    int count = 0;
                    for (int i = 0; i < _calSingalInfo.numberSignals.Count; i++)
                    {

                        res += _calSingalInfo.numberSignals[i];
                        if (_mJietiao.FinalResult.Count - 1 < i)
                        {
                            count++;
                            continue;
                        }
                        int judeg = _mJietiao.FinalResult[i];
                        int numberSignal = _calSingalInfo.numberSignals[i];
                        if (numberSignal != judeg)
                            count++;
                    }

                    double rate = ((double)count / (double)_mJietiao.FinalResult.Count) * 100;
                    rate = Math.Round(rate, 2);

                    int TotalCount = _calSingalInfo.numberSignals.Count;
                    int OneCount = _calSingalInfo.numberSignals.Sum();
                    int ZeroCount = TotalCount - OneCount;
                    string str = null;
                    if (MPublic.ConfigModel2.signalType_modulate != 3)
                    {
                        str = string.Format("总数：{0}，1个数：{1}，0个数：{2}\r\n", TotalCount, OneCount, ZeroCount) + res;
                    }
                    else
                    {
                        str = res;
                    }
                    //显示数字信号
                    _uc_Modulation.EmitShowNumberSignal(str);
                }

                richTextBox_Result.Text = _mJietiao.GetStringASK();
            }

            #endregion

            List<double> Times = _mJietiao.Times.Skip(startShowpoints).Take(showpoints).ToList();
            List<double> Orig_Y1 = _mJietiao.Orig_Y1.Skip(startShowpoints).Take(showpoints).ToList();
            List<double> Orig_Y2 = _mJietiao.Orig_Y2.Skip(startShowpoints).Take(showpoints).ToList();
            List<double> Bao_Y1 = _mJietiao.Bao_Y1.Skip(startShowpoints).Take(showpoints).ToList();
            List<double> Bao_Y2 = _mJietiao.Bao_Y2.Skip(startShowpoints).Take(showpoints).ToList();
            List<double> Judge_X = _mJietiao.Judge_X.Select(i => (double)i).Skip(startShowpoints).Take(showpoints).ToList();
            List<double> Judge_Y = _mJietiao.Judge_Y.Select(i => (double)i).Skip(startShowpoints).Take(showpoints).ToList();
            List<double> ChouYang_X = _mJietiao.ChouYang_X.Select(i => (double)i).Skip(startShowpoints).Take(showpoints).ToList();
            List<double> ChouYang_Y = _mJietiao.ChouYang_Y.Select(i => (double)i).Skip(startShowpoints).Take(showpoints).ToList();

            if (_mJietiao.Times.Count > 0 && _mJietiao.YValues.Count > 0)
                //有效数据
                FormsPlot(formsPlot_ValidData, _mJietiao.Times, _mJietiao.YValues);
            if (ffts.XValues.Count > 0 && ffts.YValues.Count > 0)
                //FFT
                FormsPlot(formsPlot_FFT, ffts.XValues, ffts.YValues);
            //Orig
            if (Times.Count > 0 && Orig_Y1.Count > 0)
                FormsPlot(formsPlot_Orig1, Times, Orig_Y1);
            if (Times.Count > 0 && Orig_Y2.Count > 0)
                FormsPlot(formsPlot_Orig2, Times, Orig_Y2);
            //FFT
            if (_mJietiao.FFT_X1.Count > 0 && _mJietiao.FFT_Y1.Count > 0)
                FormsPlot(formsPlot_FFT1, _mJietiao.FFT_X1, _mJietiao.FFT_Y1);
            if (_mJietiao.FFT_X2.Count > 0 && _mJietiao.FFT_Y2.Count > 0)
                FormsPlot(formsPlot_FFT2, _mJietiao.FFT_X2, _mJietiao.FFT_Y2);
            //Bao
            if (Times.Count > 0 && Bao_Y1.Count > 0)
                FormsPlot(formsPlot_Bao1, Times, Bao_Y1);
            if (Times.Count > 0 && Bao_Y2.Count > 0)
                FormsPlot(formsPlot_Bao2, Times, Bao_Y2);
            if (Times.Count > 0 && Bao_Y1.Count > 0 && Bao_Y2.Count > 0)
                FormsPlot(formsPlot_Bao, Times, Bao_Y1, Times, Bao_Y2);
            //formsPlot_Judge
            if (Judge_X.Count > 0 && Judge_Y.Count > 0)
                FormsPlot(formsPlot_Judge, Judge_X, Judge_Y);
            else if(_mJietiao.JudgePoints.Count > 0)
            {
                List<double> JudgePoints_X = new List<double>();
                List<double> JudgePoints_Y = new List<double>();
                foreach (var cc in _mJietiao.JudgePoints)
                {
                    if (cc.Key <= showpoints)
                    {
                        JudgePoints_X.Add(_mJietiao.Times[cc.Key]);
                        JudgePoints_Y.Add(cc.Value);
                    }
                }

                FormsPlot(formsPlot_Judge, JudgePoints_X, JudgePoints_Y);
            }
            //ChouYang
            if (MPublic.ConfigModel2.showJudgePoint)
            {
                if (ChouYang_X.Count > 0 && ChouYang_Y.Count > 0)
                {
                    formsPlot_Judge.Plot.AddScatterPoints(ChouYang_X.ToArray(), ChouYang_Y.ToArray(), Color.Red);
                    formsPlot_Judge.Refresh();
                }
            }

            //结果
            List<double> judgeX = new List<double>();
            int x = 0;
            if (_mJietiao.FinalResult.Count > 0)
            {
                foreach (int i in _mJietiao.FinalResult)
                    judgeX.Add(x++);
            }
            else
            {
                foreach (int i in _mJietiao.ResultInfo.JudgeResult)
                    judgeX.Add(x++);
            }

            if (judgeX.Count > 0)
            {
                if (_mJietiao.FinalResult.Count > 0)
                {
                    FormsPlot(formsPlot_JieTiao, judgeX, _mJietiao.FinalResult.Select(i => (double)i).ToList());
                }
                else
                {
                    FormsPlot(formsPlot_JieTiao, judgeX, _mJietiao.ResultInfo.JudgeResult.Select(i => (double)i).ToList());
                }
            }

            #endregion
        }

        /// <summary>
        /// 电压任务完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_HasVoltageOutputCompleted(object sender, EventArgs e)
        {
            _uc_Modulation.IsStart_Export = false;
        }

        /// <summary>
        /// FormsPlot赋值
        /// </summary>
        private void FormsPlot(FormsPlot formsPlot, List<double> xValues, List<double> yValues, List<double> xValues1 = null, List<double> yValues1 = null)
        {
            formsPlot.Plot.Clear();
            if (xValues1 != null && yValues1 != null)
            {
                formsPlot.Plot.AddSignalXY(xValues.ToArray(), yValues.ToArray(), Color.Red, "Bao1");
                formsPlot.Plot.AddSignalXY(xValues1.ToArray(), yValues1.ToArray(), Color.Blue, "Bao2");
            }
            else
                formsPlot.Plot.AddSignalXY(xValues.ToArray(), yValues.ToArray());
            formsPlot.Plot.AxisAuto();
            formsPlot.Refresh();
        }

        private void btn_ViewCurve_Click(object sender, EventArgs e)
        {
            FViewCurve fViewCurve = new FViewCurve(_calSingalInfo);
            fViewCurve.ShowDialog();
        }

        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Form1_HasImportExcel(object sender, EventArgs e)
        {
            try
            {
                // 对话框
                OpenFileDialog sfd = new OpenFileDialog();
                //设置保存文件对话框的标题
                sfd.Title = "请选择要打开的的文件路径";
                //初始化保存目录，默认exe文件目录
                sfd.InitialDirectory = Application.StartupPath;
                //设置保存文件的类型
                sfd.Filter = "EXCEL|*.xlsx";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    //获得保存文件的路径
                    string filePath = sfd.FileName;

                    _yvalues = MExcel.Singleton().Excel_Import_NPOI(filePath).ToArray();

                    _calSingalInfo = new CalSingalInfo() { res = _yvalues.ToList() };

                    isImport = true;

                    MessageBox.Show("导入数据成功！", "提示");
                }
            }
            catch (Exception ex) 
            {
                Log.Error(ex, ex.Message);
            }
        }
    }
}
